今晚我想來點... 簡單一點的
這次的題目是要將陣列中的 0 移道最後面,而且不可以使用另外的陣列,一切變動都必須在原本的陣列中操作.
https://leetcode.com/problems/move-zeroes/
Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Note: that you must do this in-place without making a copy of the array.
Example 1:
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Example 2:
Input: nums = [0]
Output: [0]
Constraints:
1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1
Python 跟 Go 有簡單的方法去互換兩個變數的值.
千萬不要傻傻地用另一個 temp 變數來暫存值.
a, b = b, a
a, b = b, a
用一個指標 (slow) 指向應該存非 0 的值的位置, 所有在 slow 指標前的元素應該都不為0
另一個指標 (current) 指向現在迴圈的位置,所有在 slow 指標跟 current 指標之間的元素都為0
當迴圈時如果遇到非 0 值,則互換 slow 跟 current 位置內的值,並且將 slow 指標+1.
Python
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
slow = 0
for current in range(len(nums)):
if nums[current] != 0:
nums[slow], nums[current] = nums[current], nums[slow]
slow += 1
Go
func moveZeroes(nums []int) {
slow := 0
for current := range nums {
if nums[current] != 0 {
nums[slow], nums[current] = nums[current], nums[slow]
slow += 1
}
}
}